package com.lagou.filter.component;

import java.util.*;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


public class TPMonitor {

    private static final ScheduledExecutorService scheduledExecutor = Executors.newSingleThreadScheduledExecutor();

    public static void start() {
        scheduledExecutor.scheduleAtFixedRate(() -> {
            long staticsTime = System.currentTimeMillis();
            Set<Map.Entry<String, ConcurrentLinkedDeque<ConsumerMetrics.Metrics>>> entries = ConsumerMetrics.getInstance().getMetricsMap().entrySet();
            for (Map.Entry<String, ConcurrentLinkedDeque<ConsumerMetrics.Metrics>> urlConcurrentLinkedDequeEntry : entries) {
                List<ConsumerMetrics.Metrics> metricsList = new ArrayList<>();
                String key = urlConcurrentLinkedDequeEntry.getKey();
                ConcurrentLinkedDeque<ConsumerMetrics.Metrics> value = urlConcurrentLinkedDequeEntry.getValue();
                Iterator<ConsumerMetrics.Metrics> iterator = value.iterator();
                while (iterator.hasNext()) {
                    ConsumerMetrics.Metrics metrics = iterator.next();
                    if (staticsTime - metrics.getRequestTime() > 60000) {
                        iterator.remove();
                        continue;
                    }
                    if (metrics.getRequestTime() > staticsTime) {
                        break;
                    }
                    metricsList.add(metrics);
                }
                metricsList = metricsList.stream().sorted().collect(Collectors.toList());
                Double tp90Metrics = metricsList.size() * 0.90;
                Double tp99Metrics = metricsList.size() * 0.99;
                System.out.println(key + "的tp90指标:" + metricsList.get(tp90Metrics.intValue()).getCostTime() + "ms");
                System.out.println(key + "的tp99指标:" + metricsList.get(tp99Metrics.intValue()).getCostTime() + "ms");
            }
        }, 5, 5, TimeUnit.SECONDS);
    }

}
